//
//  OAuthViewController.swift
//  
//
//  Created by apple on 15/3/2.
//
//

import UIKit
import SampleNetWorks

// 登陆发送通知
var WB_Login_Notefication = "WB_Login_Notefication"

class OAuthViewController: UIViewController {


    
    let WB_API_URL_String       = "https://api.weibo.com"
    let WB_Redirect_URL_String  = "http://www.taobao.com"
    let WB_Client_ID            = "3318794890"
    let WB_Client_Secret        = "2800d387eb98727940e602ad0e14b997"
    let WB_Grant_Type           = "authorization_code"
    
    @IBOutlet weak var WebView: UIWebView!
    override func viewDidLoad() {
        super.viewDidLoad()
        loadPage()
    }


    // 加载刷新页面
    func loadPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(self.WB_Client_ID)&redirect_uri=\(self.WB_Redirect_URL_String)"
        
        let url = NSURL(string: urlString)
        self.WebView.loadRequest(NSURLRequest(URL: url!))
    }
}



/// webView的代理方法
extension OAuthViewController:UIWebViewDelegate{

    ///  c重定向
 
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let result = continueWithCode(request.URL!)
        if let code = result.code{
            // 可以换取access_token
            let params = ["client_id": WB_Client_ID,
                "client_secret": WB_Client_Secret,
                "grant_type": WB_Grant_Type,
                "redirect_uri": WB_Redirect_URL_String,
                "code": code]
            
            // 获取网络加载工具（单例）
            let net = netWorkManager()
            net.requestJSON(HTTPMethod.POST, "https://api.weibo.com/oauth2/access_token", params, completion: { (result, error) -> () in
                print((code))
                if result != nil{
                    
                    let net = AccessToken(dict: result! as! NSDictionary)
                    net.saveAccessToken()
                    
                    // 如果登陆成功，发送通知，跳转控制器
                    NSNotificationCenter.defaultCenter().postNotificationName(WB_Login_Notefication, object: nil, userInfo: nil)
 
                }
                
            })
            
        }
        if !result.load{
            // 不用加载当前URl的页面，但是如果点击了取消按钮（获得了授权刷新权限）
            if result.reloadPage{
                SVProgressHUD.showInfoWithStatus("真的不加载吗？",maskType: SVProgressHUDMaskType.Gradient)
                loadPage()
            }
        }
        
        return result.load
    }


///  根据URL判断是否继续加载页面
///
///  :param: url 网址
func continueWithCode(url:NSURL)->(load:Bool,code:String?,reloadPage: Bool){
    // 1. 将url转换成字符串
    let urlString = url.absoluteString!
    
    // 2. 如果不是微博的 api 地址，都不加载
    if !urlString.hasPrefix(self.WB_API_URL_String) {
        // 3. 如果是回调地址，需要判断 code ithema.com
        if urlString.hasPrefix(WB_Redirect_URL_String) {
            if let query = url.query {
                let codestr: NSString = "code="
                
                // 访问新浪微博授权的时候，带有回调地址的url只有两个，一个是正确的，一个是错误的！
                if query.hasPrefix(codestr as String) {
                    var q = query as NSString!
                    return (false, q.substringFromIndex(codestr.length), false)
                } else {
                    return (false, nil, true)
                }
            }
        }
        
        return (false, nil, false)
    }
    
    return (true, nil, false)
}

}


